<?php
/**
 * Created by PhpStorm.
 * User: 曹旺
 * Date: 2018-05-10
 * Time: 14:06
 */

namespace app\index\controller;

use app\index\model\ProjectSchedule;
use app\index\model\TypeApprove;
use think\Controller;

class Project extends Base
{

    /*----------------------新增工程和进度页面-----------------------------*/
    /**
     * @return mixed
     * 添加工程项目
     * @author  曹旺
     * @data  11:10
     */
    public function add()
    {
        return $this->fetch();
    }

    /**
     * @return mixed
     * 工程项目的进度申请页面
     * @author  曹旺
     * @data  11:08
     */
    public function schedule_approve()
    {
        $ProjectScheduleModel = new ProjectSchedule();
        $ProjectFlow = $ProjectScheduleModel->flow_project_schedule_apply();
        //dump($ProjectFlow);die;
        $Project = new \app\index\model\Project();
        $ProjectName = $Project->field('id ,project_name')->where(['project_state' => 1])->select()->toArray();
        $this->assign('ProjectName', $ProjectName);
        $this->assign('ProjectFlow', $ProjectFlow);
        return $this->fetch();
    }

    /*----------------------------工程进度审批和申请列表页面及数据-------------------------------------------*/
    /**
     * @return array
     * （没有搜索功能）
     * 工程项目进度的申请列表页面的table的数据接口
     * @author  曹旺
     * @data  17:08
     */
    public function schedule_approve_list_table()
    {
        session_start();
        if (isset($_SESSION['id'])) {
            //判断用户id
            $page = input('get.page');
            if ($page == '') {
                $page = 1;
            }
            $num = input('get.limit');
            if ($num == '') {
                $num = 10;
            }
            $user_id = $_SESSION['id'];
            $where = 'state = 1 and project_user_id=' . $user_id;
            //取相关数据
            $ProjectSchedule = new ProjectSchedule();
            $res = $ProjectSchedule->schedule_approve_list_table($where, $page, $num);
            //dump($res);
            return $res;
        } else {

        }
    }

    /**
     * @return mixed
     * 工程项目进度的申请列表页面
     * @author  曹旺
     * @data  15:46
     */
    public function schedule_approve_list()
    {
        return $this->fetch();
    }

    /**
     * @return mixed
     * 我的工程进度审批列表
     * @author  曹旺
     * @data  17:04
     */
    public function schedule_apply_list()
    {
        session_start();
        $where = 'state = 1';
        if ($this->request->isPost()) {
            $id = input('post.id');
        } else {
            $id = '';
        }
        //判断用户id
        //dump($id);
        //$where = 'state = 1 and project_user_id=' . $user_id.' and id='.$id;
        //取相关数据
        $ProjectSchedule = new ProjectSchedule();
        $project = $ProjectSchedule->schedule_approve_list($where, $id);
        //dump($project);
        $this->assign('project', $project);
        return $this->fetch();
    }

    /*----------------------------工程列表、新增工程、页面数据处理---------------------------------*/
    /**
     * @return false|int $data为json  工程项目的相关内容
     * 添加工程项目数据处理
     * @author  曹旺
     * @data  11:06
     */
    public function items()
    {
        if ($this->request->isPost()) {
            session_start();
            //获取工程项目数据的json串
            $data = input('post.data');
            $dataArray = json_decode($data, true);
            //获取user_id
            $dataArray['user_id'] = $_SESSION['id'];
            $ProjectModel = new \app\index\model\Project();
            //插入数据
            $res = $ProjectModel->save($dataArray);
            return $res;
        }

    }

    /**
     * 工程项目进度申请数据的处理
     * @author  曹旺
     * @data  11:35
     */
    public function schedule_approve_sub()
    {
        if ($this->request->isPost()) {
            session_start();
            $data = input('post.data');
            $dataArray = json_decode($data, true);
            //项目进度所述的工程项目id必须存在切不为空 并且流程id也不能为空切存在
            if ($dataArray['project_id']=='' || $dataArray['project_flow_id']==''){
                return 0;
            }
            $id = $_SESSION['id'];
            //return $dataArray;
            $ProjectModel = new \app\index\model\ProjectSchedule();
            $result = $ProjectModel->schedule_apply_sub($dataArray, $id);
            return $result;
        }
    }

    /**
     * @return mixed
     * 工程列表
     * @author  曹旺
     * @data  17:04
     */
    public function project()
    {
        return $this->fetch();
    }

    /**
     * @return mixed
     * 工程所有进度详情或具体进度详情
     * @author  曹旺
     * @data  16:22
     */
    public function project_info()
    {
        $id = input('get.project_id');
        $schedule_id=input('get.schedule_id');
        $ProjectModel = new \app\index\model\Project();
        //根据ID去对应项目工程
        $projectObj = $ProjectModel::get($id);
        $project = $projectObj->toArray();
        //已累计付款
        $PayMoney = 0;
        $ProjectScheduleModel = new ProjectSchedule();
        //取项目工程所对应的进度
        if (isset($schedule_id) && $schedule_id!=''){
            //取指定工程的进度
            $where=['project_id' => $projectObj->id, 'apply_success' => 1,'id'=>$schedule_id];
        }else{
            //取项目工程的最新进度
            $where=['project_id' => $projectObj->id, 'apply_success' => 1];
        }
        $schedules = $ProjectScheduleModel->where($where)->order('project_pay_time ASC')->select()->toArray();
        foreach ($schedules as $key => $value) {
            $PayMoney = $PayMoney + $value['money'] + abs($value['additional_deductions']);
        }
        //已完成进度的个数
        $num = count($schedules) + 1;
        $schedule['apply_state']='';
        if ($num>1){
            //取项目工程的最新进度
            $schedule = $ProjectScheduleModel->where($where)->order('project_pay_time DESC')->find()->toArray();
            $scheduleArray = json_decode($schedule['apply_state'], true);
            foreach ($scheduleArray as $kk => $vv) {
                $role = \app\index\model\Role::get($vv['role']);
                $scheduleArray[$kk]['role'] = $role->role;
                $scheduleArray[$kk]['audit_time'] = date("Y-m-d H:i:s", $scheduleArray[$kk]['audit_time']);
            }
            $schedule['apply_state'] = $scheduleArray;
        }
        $project['paymoney'] = $PayMoney;
        $project['paymoneyrate'] = (round($PayMoney / $project['project_money'], 4) * 100) . "%";
        $project['num'] = $num;
        $this->assign('project', $project);
        $this->assign('schedules', $schedules);
        $this->assign('schedule', $schedule);
        return $this->fetch();
    }

    /**
     * @return array
     * 工程列表（table）数据接口
     * @author  曹旺
     * @data  17:29
     */
    public function schedule_list()
    {
        $page = input('get.page');
        if ($page == '') {
            $page = 1;
        }
        $num = input('get.limit');
        if ($num == '') {
            $num = 10;
        }
        $Project = new \app\index\model\Project();
        $datas = $Project->field('id,project_name,project_address,
        project_contract_code,project_supplier,project_money,created_time')
            ->where('project_state=1')->page($page, $num)->order('id DESC')->select()->toArray();
        $count = $Project->where('project_state=1')->count();
        $data = ['code' => 0, 'msg' => '', 'count' => $count];
        $data['data'] = $datas;
        return $data;
    }

    /**
     * @return int
     * 工程项目删除
     * @author  曹旺
     * @data  09:09
     */
    public function project_del()
    {
        $id = input('post.id');
        $res = \app\index\model\Project::destroy($id);
        return $res;
    }

    /*-----------------------------工程进度修改页面及详情--------------------------------------------*/
    /**
     * @return false|int
     *  被驳回的工程项目进度修改
     * @author  曹旺
     * @data  09:57
     */
    public function schedule_approve_save()
    {
        $dataJson = input('post.data');
        $data = json_decode($dataJson, true);
        $scheduleInfo = ProjectSchedule::get($data['id']);
        $applyStateJson = json_decode($scheduleInfo['apply_state'], true);
        $applyStateJson[count($applyStateJson) - 1]['user_id'] = '';
        $applyStateJson[count($applyStateJson) - 1]['audit_opinion'] = '';
        $applyStateJson[count($applyStateJson) - 1]['audit_time'] = '';
        $applyStateJson[count($applyStateJson) - 1]['audit_name'] = '';
        $applyStateJson[count($applyStateJson) - 1]['state'] = 0;
        //$datasArray[]=$datas;
        $data['apply_state'] = json_encode($applyStateJson);
        $data['apply_success'] = 0;
        $res = $scheduleInfo->save($data);
        return $res;
    }

    /**
     * @return mixed
     * 工程项目申请详情（被驳回时为修改）
     * @author  曹旺
     * @data  09:18
     */
    public function schedule_approve_info()
    {
        //项目进度id
        $ProjectScheduleId = input('get.id');
        $ProjectScheduleModel = new ProjectSchedule();
        //取项目进度的相关信息
        $ProjectScheduleInfo = $ProjectScheduleModel::get($ProjectScheduleId);
        $stateApply = json_decode($ProjectScheduleInfo->apply_state, true);
        $count = count($stateApply) - 1;
        if (count($stateApply) == 1 && $stateApply['0']['state'] == 2) {
            $state = 1;
        } else {
            $state = 0;
        }
        if ($stateApply[$count]['state'] == 2) {
            $ProjectScheduleInfo['apply_state'] = $stateApply[$count]['audit_opinion'];
        } else {
            $ProjectScheduleInfo['apply_state'] = '';
        }
        $Project = new \app\index\model\Project();
        //取项目相关信息（用到项目名和ID）
        $ProjectName = $Project::all([$ProjectScheduleInfo['project_id']]);
        if ($state == 1) {
            $ProjectFlow = $ProjectScheduleModel->flow_project_schedule_apply();
        } else {
            $ProjectFlow = $ProjectScheduleModel->flow_project_schedule_apply($ProjectScheduleInfo['project_flow_id']);
        }
        //dump($ProjectName);
        //dump($ProjectFlow);die;
        //$ProjectName=$Project->field('id ,project_name')->where(['project_state'=>1])->select()->toArray();
        $this->assign('ProjectName', $ProjectName);
        $this->assign('ProjectFlow', $ProjectFlow);
        $this->assign('ProjectScheduleInfo', $ProjectScheduleInfo);
        $this->assign('state', $state);
        return $this->fetch();
    }

    /*-------------------------------删除------------------------*/


    /**
     * @return $this|int
     * 工程进度审批列表软删除
     * @author  曹旺
     * @data  09:56
     */
    public function schedule_del()
    {
        //return 1;
        if ($this->request->isPost()) {
            $id = input('post.id');
            //return $id;
            $ProjectSchedule = new ProjectSchedule();
            //return $ProjectSchedule;
            $res = $ProjectSchedule->field('apply_state')->where(['id' => $id])->find();
            //return $res;
            $apply_state = json_decode($res['apply_state'], true);
            $count_apply_state = count($apply_state) - 1;
            //return $count_apply_state;
            if ($apply_state[$count_apply_state]['state'] == 0) {
                $result = $ProjectSchedule::destroy($id);
                //$result = Db::table('oa_expense_reimbursement')->delete(['id' => $id]);
                return $result;
            }
            if ($apply_state[$count_apply_state]['state'] == 1 || $apply_state[$count_apply_state]['state'] == 2) {
                $result = $ProjectSchedule->where(['id' => $id])->update(['state' => 0]);
                return $result;
            }
        }
    }

    /*---------------------------审批详情及数据处理-----------------------*/

    /**
     * @return mixed
     * 工程项目申批详情
     * @author  曹旺
     * @data  09:12
     */
    public function schedule_apply_info()
    {
        //项目进度id
        $ProjectScheduleId = input('get.id');
        $ProjectScheduleModel = new ProjectSchedule();
        //取项目进度的相关信息
        $ProjectScheduleInfo = $ProjectScheduleModel::get($ProjectScheduleId);
        $Project = new \app\index\model\Project();
        //取项目相关信息（用到项目名和ID）
        $ProjectName = $Project::get($ProjectScheduleInfo['project_id']);
        //dump($ProjectName);
        $ProjectFlow = $ProjectScheduleModel->flow_project_schedule_apply($ProjectScheduleInfo['project_flow_id']);
        //dump($ProjectFlow);die;
        //$ProjectName=$Project->field('id ,project_name')->where(['project_state'=>1])->select()->toArray();
        $this->assign('ProjectName', $ProjectName);
        $this->assign('ProjectFlow', $ProjectFlow);
        $this->assign('ProjectScheduleInfo', $ProjectScheduleInfo);
        return $this->fetch();
    }

    /**
     * @return false|int
     * 同意审批进度数据处理
     * @author  曹旺
     * @data  15:05
     */
    public function schedule_apply_agree()
    {
        session_start();
        //申请数据的id
        $id = input('post.id');
        //审批意见
        $audit_opinion = input('post.audit_opinion');
        if ($audit_opinion == '') {
            $audit_opinion = '无';
        }
        //审批用户的id
        $user_id = $_SESSION['id'];
        //用户拥有的角色
        $user_role = model('UserRole')->field('role_id')->where(['user_id' => $user_id, 'state' => 1])->select()->toArray();
        //申请数据
        /*$apply_state = model('ProjectSchedule')->field('apply_state,project_flow_id')->where(['id' => $id])
            ->find();*/
        $apply_state = ProjectSchedule::get($id);
        //取对应审批流程
        //$flow=model('Flow')->get($apply_state['project_flow_id'])->toArray();
        $flow = model('Flow')->field('first,second,third,fourth,fifth,sixth,seventh,eighth,ninth,tenth')
            ->where(['id' => $apply_state['project_flow_id']])->find()->toArray();
        //取对应审批流程的审批次数
        $flow_num = count(array_filter($flow));
        //取对应审批流程审批的审批级别（取键名）
        $flow_key = array_keys($flow);
        $flow_key_num = count($flow_key);
        $apply_state_array = json_decode($apply_state['apply_state'], true);
        //取出json串中数组的个数（审批的个数）
        $count = count($apply_state_array);
        //当前审批的下标
        $index = $count - 1;
        //return $index;
        foreach ($user_role as $key => $value) {
            if ($apply_state_array[$index]['role'] == $flow[$apply_state_array[$index]['role_key']] && $apply_state_array[$index]['role'] == $value['role_id']) {
                //判断流程的级数不能大于审批的次数
                if ($flow_num > $count) {
                    if ($apply_state_array[$index]['state'] == 1) {
                        return 2;
                    }
                    if ($apply_state_array[$index]['state'] == 2) {
                        return 3;
                    }
                    $apply_state_array[$index]['user_id'] = $user_id;
                    $apply_state_array[$index]['audit_opinion'] = $audit_opinion;
                    $apply_state_array[$index]['audit_time'] = time();
                    $apply_state_array[$index]['audit_name'] = $_SESSION['ch_name'];
                    $apply_state_array[$index]['state'] = 1;
                    for ($i = 0; $i < $flow_key_num; $i++) {
                        if ($flow_key[$i] == $apply_state_array[$index]['role_key']) {
                            $apply_state_array[$count]['role'] = $flow[$flow_key[$i + 1]];
                            $apply_state_array[$count]['user_id'] = '';
                            $apply_state_array[$count]['role_key'] = $flow_key[$i + 1];
                            $apply_state_array[$count]['audit_opinion'] = '';
                            $apply_state_array[$count]['audit_time'] = '';
                            $apply_state_array[$count]['audit_name'] = '';
                            $apply_state_array[$count]['state'] = 0;
                        }
                    }
                    $apply_state_json = json_encode($apply_state_array);
                    $apply_state_new['apply_state'] = $apply_state_json;
                    $result = $apply_state->save($apply_state_new);
                    //$result = Db::table('oa_expense_reimbursement')->where(['id' => $id])->update($apply_state_new);
                    return $result;
                } else {
                    if ($apply_state_array[$index]['state'] == 1) {
                        return 2;
                    }
                    if ($apply_state_array[$index]['state'] == 2) {
                        return 3;
                    }
                    $apply_state_array[$index]['user_id'] = $user_id;
                    $apply_state_array[$index]['audit_opinion'] = $audit_opinion;
                    $apply_state_array[$index]['audit_time'] = time();
                    $apply_state_array[$index]['audit_name'] = $_SESSION['ch_name'];
                    $apply_state_array[$index]['state'] = 1;
                    $apply_state_json = json_encode($apply_state_array);
                    $apply_state_new['apply_state'] = $apply_state_json;
                    $apply_state_new['apply_success'] = 1;
                    $result = $apply_state->save($apply_state_new);
                    //$result = Db::table('oa_expense_reimbursement')->where(['id' => $id])->update($apply_state_new);
                    return $result;
                }
            } else {
                if ($key == (count($user_role) - 1)) {
                    return 2;
                }
            }
        }
    }

    /**
     * @return false|int
     * 驳回进度审批数据处理
     * @author  曹旺
     * @data  15:14
     */
    public function schedule_apply_disagree()
    {
        session_start();
        //申请数据的id
        $id = input('post.id');
        //审批意见
        $audit_opinion = input('post.audit_opinion');
        if ($audit_opinion == '') {
            $audit_opinion = '无';
        }
        //审批用户的id
        $user_id = $_SESSION['id'];
        //用户拥有的角色
        $user_role = model('UserRole')->field('role_id')->where(['user_id' => $user_id, 'state' => 1])->select()->toArray();
        //申请数据
        /*$apply_state = model('ProjectSchedule')->field('apply_state,project_flow_id')->where(['id' => $id])
            ->find();*/
        $apply_state = ProjectSchedule::get($id);
        //取对应审批流程
        //$flow=model('Flow')->get($apply_state['project_flow_id'])->toArray();
        $flow = model('Flow')->field('first,second,third,fourth,fifth,sixth,seventh,eighth,ninth,tenth')
            ->where(['id' => $apply_state['project_flow_id']])->find()->toArray();
        //取对应审批流程的审批次数
        $flow_num = count(array_filter($flow));
        //取对应审批流程审批的审批级别（取键名）
        $flow_key = array_keys($flow);
        $flow_key_num = count($flow_key);
        $apply_state_array = json_decode($apply_state['apply_state'], true);
        //取出json串中数组的个数（审批的个数）
        $count = count($apply_state_array);
        //当前审批的下标
        $index = $count - 1;
        //return $index;
        foreach ($user_role as $key => $value) {
            if ($apply_state_array[$index]['role'] == $flow[$apply_state_array[$index]['role_key']] && $apply_state_array[$index]['role'] == $value['role_id']) {
                //判断流程的级数不能大于审批的次数
                if ($apply_state_array[$index]['state'] == 1) {
                    return 3;
                }
                if ($apply_state_array[$index]['state'] == 2) {
                    return 2;
                }
                $apply_state_array[$index]['user_id'] = $user_id;
                $apply_state_array[$index]['audit_opinion'] = $audit_opinion;
                $apply_state_array[$index]['audit_time'] = time();
                $apply_state_array[$index]['audit_name'] = $_SESSION['ch_name'];
                $apply_state_array[$index]['state'] = 2;
                $apply_state_json = json_encode($apply_state_array);
                $apply_state_new['apply_state'] = $apply_state_json;
                $apply_state_new['apply_success'] = 2;
                $result = $apply_state->save($apply_state_new);
                //$result = Db::table('oa_expense_reimbursement')->where(['id' => $id])->update($apply_state_new);
                return $result;

            } else {
                if ($key == (count($user_role) - 1)) {
                    return 3;
                }
            }
        }
    }


    /*------------------------------------------------------------------*/
    public function demo()
    {
        $model = new ProjectSchedule();
        $res = $model->order('created_time DESC')->select()->toArray();
        dump($res);
        die;
        echo time();
        die;
        $aaa = new ProjectSchedule();
        $ww = $aaa->save($data);
        dump($ww);
        die;
        $model = new \app\index\model\Project();
        $res = $model::get($data['id']);
        //$res['project_name']=$data['project_name'];
        $arr = $res->save($data);
        dump($arr);
        die;
        session_start();
        $id = $_SESSION['id'];
        $dataArray['project_flow_id'] = 27;
        $ProjectModel = new \app\index\model\UserRole();
        $arr = $ProjectModel->with('role')->where('user_id=' . $id)->select()->toArray();
        dump($arr);
        $TtpeApproveModel = new TypeApprove();
        $res = $TtpeApproveModel->with('projectschedule')->select()->toArray();
        //$result=$ProjectModel->schedule_apply_sub($dataArray,$id);
        dump($res);
        $ProjectScheduleModel = new ProjectSchedule();
        $ress = $ProjectScheduleModel->with('typeapprove')->select()->toArray();
        dump($ress);
        $ass = \app\index\model\Role::get(1);
        dump($ass->id);

    }

}